package org.springblade.tms.config;

import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.Enumerator;
import org.springblade.tms.global.anno.SelectEnum;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.config
 * @className: GlobalVariableRunner
 * @author: yr
 * @description:
 * @date: 2022/3/11 16:02
 */
@Component
@Slf4j
public class GlobalVariableRunner implements ApplicationRunner {

	private static final String BASE_PACKAGE = "org.springblade.tms.global.enums";

	private static final String RESOURCE_PATTERN = "/**/*.class";

	protected static final Map<String, Class<? extends Enumerator>> selectEnumMap = new HashMap<>();


	@Override
	public void run(ApplicationArguments args) throws Exception {

		/************枚举 - 下拉**************/
		//spring工具类，可以获取指定路径下的全部类
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
			ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + RESOURCE_PATTERN;
		Resource[] resources = resourcePatternResolver.getResources(pattern);
		//MetadataReader 的工厂类
		MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
		for (Resource resource : resources) {
			//用于读取类信息
			MetadataReader reader = readerfactory.getMetadataReader(resource);
			//扫描到的class
			String classname = reader.getClassMetadata().getClassName();
			Class<?> clazz = Class.forName(classname);
			//判断是否有指定主解
			SelectEnum anno = clazz.getAnnotation(SelectEnum.class);
			if (anno != null && Enumerator.class.isAssignableFrom(clazz)) {
				//将注解中的类型值作为key，对应的类作为 value
				GlobalVariableRunner.selectEnumMap.put(anno.value(), (Class<? extends Enumerator>) clazz);
			}
		}
		log.info("枚举 - 下拉加载完成");


	}


}
